package com.yiyw.herostory.manage;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.List;

/**
 * @Author yiyw
 * @Description TODO
 * @Date 2022/8/14 14:30
 **/
public final class ChannelGroupManage {

    /***
     * 定义 channel 集合，收集所有的 channel 信息
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private ChannelGroupManage() {

    }

    public static void addChannel(Channel channel) {
        if (null != channel) {
            channelGroup.add(channel);
        }
    }

    public static void removeChannel(Channel channel) {
        if (null != channel) {
            channelGroup.remove(channel);
        }
    }

    /***
     * Title: getUserIdByChannel
     * @author yiyw
     * @description 获取用户 ID
     * @createTime  2022/8/14 14:57
     * @param channel
     * @return int
     */
    public static int getUserIdByChannel(Channel channel) {
        Integer userId = (Integer) channel.attr(AttributeKey.valueOf("userId")).get();
        if (null != userId) {
            return userId.intValue();
        }
        return -1;
    }

    public static void bingUserIdToChannel(Channel channel, Integer userId) {
        // 将 channel 绑定用户Id
        channel.attr(AttributeKey.valueOf("userId")).set(userId);
    }

    public static void writeAndFlush(Object msg) {
        channelGroup.writeAndFlush(msg);
    }


}
